package com.dk.bleNfc.DeviceManager;

import android.bluetooth.*;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

public class BleHelper {

    public interface BLEListener {
        void onBluetoothReady();
        void onDeviceFound(BluetoothDevice device);
        void onDeviceConnected();
        void onDeviceDisconnected();
        void onServicesDiscovered();
        void onDataReceived(byte[] data);
        void onError(String message);
    }

    private static final String TAG = "BLEHelper";

    // 你可以根据你的 BLE 设备修改这些 UUID！！！
    // 以下是示例 UUID，请替换成你的 BLE 设备的服务 UUID 和特征 UUID
    private static final UUID SERVICE_UUID = UUID.fromString("0000FFF0-0000-1000-8000-00805F9B34FB"); // 示例服务 UUID
    private static final UUID CHARACTERISTIC_UUID = UUID.fromString("0000FFFE-0000-1000-8000-00805F9B34FB"); // 示例特征 UUID（可读写/通知）

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner bluetoothLeScanner;
    private BluetoothGatt bluetoothGatt;
    private BluetoothDevice targetDevice;

    private final CopyOnWriteArrayList<BLEListener> listeners = new CopyOnWriteArrayList<>();
    private final Context context;

    public BleHelper(Context context) {
        this.context = context.getApplicationContext();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            notifyError("设备不支持蓝牙");
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        }
        notifyBluetoothReady();
    }

    public void addListener(BLEListener listener) {
        if (listener != null && !listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    public void removeListener(BLEListener listener) {
        listeners.remove(listener);
    }

    public void startScan() {
        if (bluetoothLeScanner == null) {
            notifyError("不支持 BLE 扫描");
            return;
        }

        notifyBluetoothReady();
        bluetoothLeScanner.startScan(scanCallback);
        //Log.d(TAG, "开始扫描 BLE 设备");
    }

    public void stopScan() {
        if (bluetoothLeScanner != null) {
            bluetoothLeScanner.stopScan(scanCallback);
            //Log.d(TAG, "停止扫描 BLE 设备");
        }
    }

    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            String name = device.getName();
            String address = device.getAddress();
            //Log.d(TAG, "发现 BLE 设备: " + name + " / " + address);

            for (BLEListener listener : listeners) {
                listener.onDeviceFound(device);
            }
            // 示例：自动连接某个设备（你也可以自己决定何时连接）
            // 比如根据设备名或 MAC 地址
            if ("Bluetooth remote".equals(name)) {
                stopScan();
                connectToDevice(device);
            } else if (address != null && address.equalsIgnoreCase("XX:XX:XX:XX:XX:XX")) {
                stopScan();
                connectToDevice(device);
            }
        }
    };

    // 方式1：通过 BluetoothDevice 对象连接
    public void connectToDevice(BluetoothDevice device) {
        this.targetDevice = device;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            bluetoothGatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE);
        } else {
            bluetoothGatt = device.connectGatt(context, false, gattCallback);
        }
        Log.d(TAG, "发起 BLE GATT 连接");
    }

    // 方式2：通过 MAC 地址连接（需先确保蓝牙开启）
    public void connectByMac(String mac) {
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(mac);
        connectToDevice(device);
    }

    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.d(TAG, "BLE 连接成功");
                notifyDeviceConnected();
                gatt.discoverServices(); // 发现服务
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.d(TAG, "BLE 连接断开");
                notifyDeviceDisconnected();
                bluetoothGatt = null;
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "服务发现成功");
                notifyServicesDiscovered();

                // 找到我们需要的服务与特征
                BluetoothGattService service = gatt.getService(SERVICE_UUID);
                if (service != null) {
                    BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);
                    if (characteristic != null) {
                        // 启用通知 或 直接读取 / 写入
                        gatt.setCharacteristicNotification(characteristic, true);

                        // TODO: 你也可以在这里直接读取或写入数据
                        // gatt.readCharacteristic(characteristic);
                        // writeData(gatt, characteristic, "Hello".getBytes());
                    }
                }
            } else {
                notifyError("服务发现失败，状态码: " + status);
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            // 接收到 BLE 设备推送的数据（比如按键、传感器等）
            byte[] data = characteristic.getValue();
            notifyDataReceived(data);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                byte[] data = characteristic.getValue();
                notifyDataReceived(data);
            }
        }
    };

    // 示例：向 BLE 特征写入数据（比如发送指令）
    public void writeData(byte[] data) {
        if (bluetoothGatt == null) {
            notifyError("未连接");
            return;
        }
        BluetoothGattService service = bluetoothGatt.getService(SERVICE_UUID);
        if (service == null) {
            notifyError("服务未找到");
            return;
        }
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);
        if (characteristic == null) {
            notifyError("特征未找到");
            return;
        }

        characteristic.setValue(data);
        boolean success = bluetoothGatt.writeCharacteristic(characteristic);
        Log.d(TAG, "写入数据: " + success);
    }

    private void notifyBluetoothReady() {
        for (BLEListener l : listeners) {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(l::onBluetoothReady);
        }
    }

    private void notifyDeviceFound(BluetoothDevice device) {
        for (BLEListener l : listeners) {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> l.onDeviceFound(device));
        }
    }

    private void notifyDeviceConnected() {
        for (BLEListener l : listeners) {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(l::onDeviceConnected);
        }
    }

    private void notifyDeviceDisconnected() {
        for (BLEListener l : listeners) {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(l::onDeviceDisconnected);
        }
    }

    private void notifyServicesDiscovered() {
        for (BLEListener l : listeners) {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(l::onServicesDiscovered);
        }
    }

    private void notifyDataReceived(byte[] data) {
        for (BLEListener l : listeners) {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> l.onDataReceived(data));
        }
    }

    private void notifyError(String message) {
        for (BLEListener l : listeners) {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> l.onError(message));
        }
    }

    // 断开连接
    public void disconnect() {
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
            bluetoothGatt.close();
            bluetoothGatt = null;
        }
    }
}
